


from rest_framework.throttling import SimpleRateThrottle
from django.core.cache import cache
from django.conf import settings
# 结合手机验证码接口来书写
class SMSRateThrottle(SimpleRateThrottle):
    scope = 'sms'
    def get_cache_key(self, request, view):
        # 手机号是通过get请求提交的
        mobile = request.query_params.get('mobile', None)
        if not mobile:
            return None  # 不限制

        # 手机验证码发送失败，不限制，只有发送成功才限制，如果需求是发送失败也做频率限制，就注释下方三行
        code = cache.get(settings.SMS_CACHE_KEY % {'mobile': mobile})
        if not code:
            return None

        # return self.cache_format % {
        #     'scope': self.scope,
        #     'ident': mobile,
        # }

        return 'throttle_%s_%s'%(self.scope,mobile)
